<template>
    <webview class="webview"
             ref="webviewBrowser"
             :partition="partition"
             :src="url"
             allowpopups
             useragent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
             nodeintegration></webview>
</template>

<script>
import {ipcApiRoute} from '@/api/main'
import { getLoginList,updateAccountStatus,addAccount } from "@/api/media/mediaAccount";
import CookieMixin from '@/layout/mixin/useCookie'
import { ExecuteFunc,formatCode } from "@/utils/execute"
// import { listAccount, getAccount, delAccount, addAccount, updateAccount } from "@/api/media/mediaManage";
import { Message } from "element-ui";
import { v4 as uuidv4 } from 'uuid';
export default {
  name:"mediaIfame",
  mixins: [CookieMixin],

  props: {
    url:{
      type: String,
      default:"about:blank"
    },
    partition:{
      type:String,
      default:"persist:login"
    },
    platformCode:{
      type:String,
      default:''
    }

  },

  data() {
    return {
      loading:false,
      //半个小时的检测状态
      count: 60 * 30,
      userInfo:{
        systemUniqId:undefined, //系统唯一id
        nickname:undefined, //账号昵称
        headImgUrl:undefined, //账号头像
        cookies:undefined, //登录参数
        uniqId:undefined, //唯一id
        finderUserName:undefined, //账号唯一标识
        acctType:undefined //账号类型
      }
    };
  },

  created(){

  },
  methods: {

    /**
     * 初始化webview
     */
    init(){
      this.webview = this.$refs.webviewBrowser
      this.webview.addEventListener('dom-ready', () => {
        this.webview.setZoomFactor(0.9);
      })
    },


    /**
     * 登入帐号
     * @param item
     * @returns {Promise<void>}
     */
    async handleClickSetCookies(item){
      //初始化
      this.init()
      //获取cookies
      let cookies = JSON.parse(item.cookies)
      //移除cookies
      await this.useRemoveCookies(this.url,this.partition)
      //填写cookies
      await this.useSetCookies(this.url,this.partition,cookies)
      const requestParam = ExecuteFunc[this.platformCode].getLoginStatus;
      let loginStatus = await this.webview.executeJavaScript(requestParam);
      //账号掉线后执行的逻辑
      if(loginStatus){
        //账号未掉线，视频号登录需要请求运营角色
        if (item.platformCode === "wxsph"){
          let getLocalstatus = ExecuteFunc[this.platformCode].setUserLogin;
          let res =  await  this.webview.executeJavaScript(getLocalstatus.replace("finderUsernameReplace",item['finderUserName']));
          //获取账号登录状态
        }
      }else{
       // await this.useRemoveCookies(this.url,this.partition)
        if( item.loginStatus === 1 ){
          await this.useRemoveCookies(this.url,this.partition)
          // await this.updateLoginStatus(item.id,0);
        }
        await this.loginAccount(item);
        console.log("账号未登录！")
      }
      await this.webview.reload()
      this.loading=false
    },



    /**
     * 扫码轮询获取状态
     * @returns {Promise<void>}
     */
    async  loginAccount(item){
      this.count --
      var that =this
      if(this.count > 0){
        const resStatus = ExecuteFunc[this.platformCode].getLoginStatus;
        let logStatus = await this.webview.executeJavaScript(resStatus);
        if (logStatus) {
          const cookies = await this.useGetCookies(that.url, "persist:" + item.id)
          let cookieList =   cookies.data.list;
          for(var i = 0 ; i < cookieList.length;i++){
            if(item.name !== "sessionid"){
              cookieList.slice(i);
              console.log(cookieList)
            }
          }
          const userInfoRes = await this.webview.executeJavaScript(ExecuteFunc[this.platformCode].getUserInfo)
          this.userInfo.cookies = JSON.stringify(cookies.data.list);
          this.userInfo.platformCode = this.platformCode

          //公众号
          const uuid = uuidv4();
          this.userInfo.scanRandom = uuid;

          this.userInfo.checkUniqId = item.systemUniqId
          if(this.platformCode === 'wxgzh'){
            let uniqId =  this.platformCode + userInfoRes.uin_base64;
            this.userInfo.systemUniqId = uniqId
            this.userInfo.headImgUrl = userInfoRes.avatar
            this.userInfo.nickname = userInfoRes.nick_name
            this.userInfo.uniqId = userInfoRes.uin_base64
            // this.userInfo.acctType = userInfoRes.acctType
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //视频号
          else if(this.platformCode === 'wxsph'){
            console.log(userInfoRes)
            for(let i = 0 ; i < userInfoRes.length; i++){
              let uniqId =  this.platformCode + userInfoRes[i].uniqId
              this.userInfo.systemUniqId = uniqId
              this.userInfo.headImgUrl = userInfoRes[i].headImgUrl
              this.userInfo.nickname = userInfoRes[i].nickname
              this.userInfo.uniqId = userInfoRes[i].uniqId
              this.userInfo.acctType = userInfoRes[i].acctType
              this.userInfo.finderUserName = userInfoRes[i].finderUsername
              await addAccount(this.userInfo).then( res =>{
                console.log(res)
              })
            }
          }
          //视频号加热平台
          else if(this.platformCode === 'wxsphjr'){
            let uniqId =  this.platformCode + userInfoRes.username
            this.userInfo.systemUniqId = uniqId
            this.userInfo.headImgUrl =  userInfoRes.headImgUrl
            this.userInfo.nickname = userInfoRes.nickName
            this.userInfo.acctType = 1
            this.userInfo.finderUserName = userInfoRes.username
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //微信小程序
          else if(this.platformCode === 'wxxcx'){
            let uniqId =  this.platformCode + userInfoRes.appid
            this.userInfo.systemUniqId = uniqId
            this.userInfo.headImgUrl =  userInfoRes.avatar
            this.userInfo.nickname = userInfoRes.nickname
            this.userInfo.uniqId = userInfoRes.fakeIdBase64
            this.userInfo.acctType = 1
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //小红书
          else if(this.platformCode === 'xhs'){
            let uniqId =  this.platformCode + userInfoRes.userId
            this.userInfo.systemUniqId = uniqId
            this.userInfo.headImgUrl =  userInfoRes.userAvatar
            this.userInfo.nickname = userInfoRes.userName
            this.userInfo.uniqId = userInfoRes.userId
            this.userInfo.acctType = 1
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //抖音账号
          else if(this.platformCode === 'douyin'){
            let uniqId =  this.platformCode + userInfoRes.uid
            this.userInfo.systemUniqId = uniqId
            this.userInfo.headImgUrl =  userInfoRes.avatar_larger.url_list[0]
            this.userInfo.nickname = userInfoRes.nickname
            this.userInfo.uniqId = userInfoRes.uid
            this.userInfo.acctType = 1
            await  addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //视频号小店
          else if(this.platformCode === 'sphxd'){
            let uniqId =  this.platformCode + userInfoRes.appid
            this.userInfo.systemUniqId = uniqId
            this.userInfo.headImgUrl =  userInfoRes.iconUrl
            this.userInfo.nickname = userInfoRes.nickName
            this.userInfo.uniqId = userInfoRes.appid
            this.userInfo.acctType = 1
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          // await this.useRemoveCookies(this.url, "persist:login")
          this.loginStatus = false
          this.$emit("getList")
          this.$modal.msgSuccess("账号添加成功！")
        }else{
          await this.useSleep(1000)
          await this.loginAccount(item)
        }
      }
    },





    /**
     * 修改账号的登录状态
     */
    updateLoginStatus(accountId,status){
      let jsonData = {id: accountId, status:status}
      updateAccountStatus(JSON.stringify(jsonData)).then((res)=>{
        console.log(res)
        if(res.code === 200){
          this.$emit("getList")
        }
      })
    },


    //后退
    handleClickLeft(){
      this.$refs.webviewBrowser.goBack()
    },
    //前进
    handleClickRight(){
      this.$refs.webviewBrowser.goForward()
    },
    //刷新
    handleClickReload(){
      this.$refs.webviewBrowser.reload()
    }

  }
}
</script>
<style scoped lang="scss" >

//::v-deep .el-dialog{
//  border-radius: 6px;
//}
// // .el-upload--picture-card 控制加号部分
// ::v-deep.hide .el-upload--picture-card {
//     display: none;
// }
// // 去掉动画效果
// ::v-deep .el-list-enter-active,
// ::v-deep .el-list-leave-active {
//     transition: all 0s;
// }
//
// ::v-deep .el-list-enter, .el-list-leave-active {
//   opacity: 0;
//   transform: translateY(0);
// }

//
//.dialogWapp{
//    margin-top: -20px;
//    display: flex;
//    justify-content: start;
//    flex-wrap: wrap;
//
//    .item{
//        height: 87px;
//        cursor: pointer;
//        margin: 4px;
//        text-align: center;
//
//        padding: 8px;
//        width: 88px;
//        border-radius: 6px;
//        margin-bottom: 10px;
//        img{
//            width:35px;
//            height: 35px;
//            text-align: center;
//            margin: 0 auto;
//            margin-bottom: 2px;
//        }
//        &:hover{
//            border: 1px solid #c2b3ff;
//        }
//    }
//}

.webview{
  height: calc(100vh - 157px);
  //width: 100%;
}
</style>

